<?php
namespace app\common\server;
use x\Xbase;
class UserUpLevel extends Xbase
{


    /**
     * 余额支付
     * @param  [type] $order_no [description]
     * @return [type]           [description]
     */
    public function upLevel($id,$level,$money){
        $order_no = $this->com_order_no();
        $this->db->begin();
        $mysql = [];
        $mysql[] = $this->db->update("user",["id"=>$id,"level"=>$level]);
        //查询上级
        $info = $this->db->find('user',$id);
        $s_info = [];
        $s_id = $info["s_id"];
        if($s_id){
            while (true){
                $s_info = $this->db->query("select * from user where id = ?",[$s_id],1);
                if(empty($s_info)){
                    break;
                }
                if($s_info["level"] > $level || ($s_info["level"] == 3 && $level == 3)){
                    break;
                }else if($s_info["level"] <= $level){
                    $s_id = $s_info["s_id"];
                }
            }
        }

        if($s_info){
            //升级佣金比例
            $up_level_money = c('type.up_level_money');
            $data = [
                "user_id" => $info["id"],
                "s_id" => $s_info["id"],
                "before_level" => $info["level"],
                "after_level" => $level,
                "money" => $money,
                "up_money" => $money * $up_level_money,
                "create_time" => time()
            ];
            $mysql[] = $log_id = $this->db->insert("user_up_level",$data);
            $note = "下级【" . $info["name"] . "】升级获得佣金";
            $mysql[] = m('Userbill','xcom')->doit($order_no, $s_info['id'], 109, 'user_up_level', $log_id,  $money * $up_level_money,"money",$note);
        }
        $rs = $this->db->end($mysql);
        if (!$rs) {
            return $this->setError('升级失败!');
        }
        return true;
    }

}
